package com.virtualperson.util;

import com.virtualperson.exception.ImageGenerationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Component
public class ImageFileUtil {
    private static final String IMAGE_DIR = "generated_images";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HHmmss");

    private final RestTemplate restTemplate;

    public ImageFileUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        createImageDirectory();
    }

    /**
     * 创建图片存储目录
     */
    private void createImageDirectory() {
        try {
            Path path = Paths.get(IMAGE_DIR);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
                log.info("创建图片存储目录: {}", path.toAbsolutePath());
            }
        } catch (IOException e) {
            log.error("创建图片存储目录失败", e);
            throw new ImageGenerationException("创建图片存储目录失败: " + e.getMessage());
        }
    }

    /**
     * 生成图片文件名
     * @param originalUrl 原始图片URL
     * @return 生成的文件名
     */
    private String generateFileName(String originalUrl) {
        String extension = getFileExtension(originalUrl);
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DATE_FORMATTER);
        String timeStr = now.format(TIME_FORMATTER);
        String uuid = UUID.randomUUID().toString().substring(0, 8);
        return String.format("%s_%s_%s.%s", dateStr, timeStr, uuid, extension);
    }

    /**
     * 从URL中获取文件扩展名
     * @param url 图片URL
     * @return 文件扩展名
     */
    private String getFileExtension(String url) {
        String extension = "jpg"; // 默认扩展名
        if (url != null && url.contains(".")) {
            String[] parts = url.split("\\.");
            if (parts.length > 0) {
                String lastPart = parts[parts.length - 1].toLowerCase();
                if (lastPart.matches("(jpg|jpeg|png|gif|webp)")) {
                    extension = lastPart;
                }
            }
        }
        return extension;
    }

    /**
     * 下载并保存图片
     * @param imageUrl 图片URL
     * @return 保存后的图片文件路径
     */
    public String downloadAndSaveImage(String imageUrl) {
        try {
            // 生成文件名和保存路径
            String fileName = generateFileName(imageUrl);
            String dateDir = LocalDateTime.now().format(DATE_FORMATTER);
            Path saveDir = Paths.get(IMAGE_DIR, dateDir);
            Files.createDirectories(saveDir);
            Path filePath = saveDir.resolve(fileName);

            // 下载图片
            byte[] imageBytes = restTemplate.getForObject(imageUrl, byte[].class);
            if (imageBytes == null || imageBytes.length == 0) {
                throw new ImageGenerationException("下载图片失败: 图片数据为空");
            }

            // 保存图片
            try (FileOutputStream fos = new FileOutputStream(filePath.toFile())) {
                fos.write(imageBytes);
            }

            log.info("图片已保存: {}", filePath.toAbsolutePath());
            return filePath.toString();
        } catch (Exception e) {
            log.error("保存图片失败: url={}", imageUrl, e);
            throw new ImageGenerationException("保存图片失败: " + e.getMessage());
        }
    }

    /**
     * 获取图片存储目录的绝对路径
     * @return 图片存储目录的绝对路径
     */
    public String getImageDirectoryPath() {
        return Paths.get(IMAGE_DIR).toAbsolutePath().toString();
    }

    /**
     * 清理指定天数之前的图片
     * @param days 天数
     */
    public void cleanupOldImages(int days) {
        try {
            Path imageDir = Paths.get(IMAGE_DIR);
            if (!Files.exists(imageDir)) {
                return;
            }

            LocalDateTime cutoffDate = LocalDateTime.now().minusDays(days);
            String cutoffDateStr = cutoffDate.format(DATE_FORMATTER);

            Files.list(imageDir)
                .filter(Files::isDirectory)
                .filter(path -> {
                    String dirName = path.getFileName().toString();
                    return dirName.compareTo(cutoffDateStr) < 0;
                })
                .forEach(path -> {
                    try {
                        Files.walk(path)
                            .sorted((p1, p2) -> -p1.compareTo(p2))
                            .forEach(p -> {
                                try {
                                    Files.delete(p);
                                } catch (IOException e) {
                                    log.warn("删除文件失败: {}", p, e);
                                }
                            });
                        log.info("已删除过期目录: {}", path);
                    } catch (IOException e) {
                        log.error("清理过期图片失败: {}", path, e);
                    }
                });
        } catch (IOException e) {
            log.error("清理过期图片失败", e);
        }
    }
} 